package com.dd.cloud.user.service.doctor.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.OrderConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.BigDecimalUtils;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.common.utils.ObjectUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.vo.PageVo;
import com.dd.cloud.user.entity.consult.ConsultSubscribe;
import com.dd.cloud.user.entity.doctor.DoctorDetail;
import com.dd.cloud.user.entity.doctor.DoctorOrderIncomeDetail;
import com.dd.cloud.user.entity.doctor.DoctorUser;
import com.dd.cloud.user.entity.finance.FinanceRatioSet;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.pres.PresPrescription;
import com.dd.cloud.user.mapper.doctor.DoctorOrderIncomeDetailMapper;
import com.dd.cloud.user.req.doctor.*;
import com.dd.cloud.user.res.doctor.*;
import com.dd.cloud.user.service.consule.IConsultSubscribeService;
import com.dd.cloud.user.service.doctor.IDoctorDetailService;
import com.dd.cloud.user.service.doctor.IDoctorOrderIncomeDetailService;
import com.dd.cloud.user.service.doctor.IDoctorUserService;
import com.dd.cloud.user.service.finance.IFinanceRatioSetService;
import com.dd.cloud.user.service.order.IOrderPayService;
import com.dd.cloud.user.service.pres.IPresPrescriptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class DoctorOrderIncomeDetailServiceImpl extends ServiceImpl<DoctorOrderIncomeDetailMapper, DoctorOrderIncomeDetail> implements IDoctorOrderIncomeDetailService {
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IDoctorDetailService doctorDetailService;
    @Autowired
    private IPresPrescriptionService presPrescriptionService;
    @Autowired
    private IFinanceRatioSetService financeRatioSetService;
    @Autowired
    private IConsultSubscribeService consultSubscribeService;
    @Autowired
    private IOrderPayService orderPayService;
    @Value("${afterTaxScale}")
    private BigDecimal afterTaxScale;

    /**
     * 查询医生收入明细 年统计
     *
     * @param req
     * @return
     */
    @Override
    public PageVo<DoctorOrderIncomeDetailListRes> queryDoctorOrderIncomeDetailList(DoctorOrderIncomeDetailListReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        QueryWrapper<DoctorUser> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorUser::getId, loginInfo.getId());
        qw.lambda().select(DoctorUser::getCreateDate);
        DoctorUser doctorUser = doctorUserService.getOne(qw);
        LocalDateTime createDate = doctorUser.getCreateDate();
        LocalDateTime now = LocalDateTime.now();
        int total = now.getYear() - createDate.getYear() + 1;
        PageVo<DoctorOrderIncomeDetailListRes> pageVo = req.pageVoPojo();
        pageVo.setTotal(total);
        long offset = pageVo.offset();
        LocalDateTime start = LocalDateTime.of(Math.toIntExact((now.getYear() - offset - pageVo.getSize() + 1)), 1, 1, 0, 0);
        start = start.compareTo(createDate) < 0 ? createDate : start;
        LocalDateTime end = LocalDateTime.of(Math.toIntExact((now.getYear() - offset)), 12, 31, 23, 59, 59);
        end = end.compareTo(now) > 0 ? LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 23, 59, 59) : end;
        req.setDoctorId(loginInfo.getId());
        req.setStart(start);
        req.setEnd(end);
        int year1 = start.getYear();
        int year2 = end.getYear();
        int month1 = start.getMonthValue();
        int month2 = end.getMonthValue();
        List<DoctorOrderIncomeDetailListRes> list = getBaseMapper().queryDoctorOrderIncomeDetailList(req);
        Map<String, DoctorOrderIncomeDetailListRes> map = list.stream().collect(Collectors.toMap(t -> t.getYearNum() + "" + t.getMonthNum(), t -> t));
        List<DoctorOrderIncomeDetailListRes> res = new ArrayList<>(36);
        for (int i = year2; i >= year1; i--) {
            int min;
            int max;
            if (i == year2) {
                max = month2;
                min = 1;
            } else if (i == year1) {
                max = 12;
                min = month1;
            } else {
                max = 12;
                min = 1;
            }
            for (int j = max; j >= min; j--) {
                DoctorOrderIncomeDetailListRes temp = map.get(i + "" + j);
                if (temp == null) {
                    temp = new DoctorOrderIncomeDetailListRes();
                    temp.setYearNum(i);
                    temp.setMonthNum(j);
                    temp.setTotalIncome(0);
                }
                res.add(temp);
            }
        }
        pageVo.setRecords(res);
        if (req.getStatistics() == 1) {
            pageVo.setExtend(getBaseMapper().queryDoctorOrderIncomeDetailListTotal(req));
            pageVo.setExtend(pageVo.getExtend() == null ? 0 : pageVo.getExtend());
        }
        return pageVo;
    }

    /**
     * 查询医生收入明细 月明细
     *
     * @param req
     * @return
     */
    @Override
    public PageVo<DoctorOrderIncomeDetailMonthListRes> queryDoctorOrderIncomeDetailMonthList(DoctorOrderIncomeDetailMonthListReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        req.setDoctorId(loginInfo.getId());
        PageVo<DoctorOrderIncomeDetailMonthListRes> pageVo = req.pageVoPojo();
        pageVo = getBaseMapper().queryDoctorOrderIncomeDetailMonthList(pageVo, req);
        if (req.getStatistics() == 1) {
            DoctorOrderIncomeDetailExtendRes extendRes = getBaseMapper().queryDoctorOrderIncomeDetailMonthTotal(req);
            if (extendRes == null) {
                extendRes = new DoctorOrderIncomeDetailExtendRes();
            }
            if (extendRes.getRefund() != null) {
                extendRes.setRefund(~extendRes.getRefund() + 1);
            }
            pageVo.setExtend(extendRes);
        }
        return pageVo;
    }

    /**
     * 查询医生收入记录 运营后台
     *
     * @param req
     * @return
     */
    @Override
    public PageVo<DoctorOrderIncomeDetailPageSystemRes> queryDoctorOrderIncomeDetailPageSystem(DoctorOrderIncomeDetailPageSystemReq req) {
        UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        PageVo<DoctorOrderIncomeDetailPageSystemRes> pageVo = req.pageVoPojo();
        pageVo = getBaseMapper().queryDoctorOrderIncomeDetailPageSystem(pageVo, req);
        if (req.getStatistics() == 1) {
            pageVo.setExtend(queryDoctorWithdrawIncomeInfo(req.getDoctorId()));
        }
        return pageVo;
    }

    /**
     * 导出医生收入记录 运营后台
     *
     * @param response
     * @param req
     */
    @Override
    public void exportDoctorOrderIncomeDetailSystemExcel(HttpServletResponse response, DoctorOrderIncomeDetailPageSystemReq req) {
        int no = 1;
        req.setPage(1);
        req.setPageSize(100);
        DoctorDetailRes doctorDetail = doctorDetailService.queryDoctorDetail(req.getDoctorId());
        PageVo<DoctorOrderIncomeDetailPageSystemRes> iPage;
        List<DoctorOrderIncomeDetailSystemExcelRes> listRes = new ArrayList<>(100);
        do {
            iPage = req.pageVoPojo();
            iPage = getBaseMapper().queryDoctorOrderIncomeDetailPageSystem(iPage, req);
            for (DoctorOrderIncomeDetailPageSystemRes item : iPage.getRecords()) {
                DoctorOrderIncomeDetailSystemExcelRes res = new DoctorOrderIncomeDetailSystemExcelRes();
                BeanUtils.copyProperties(item, res);
                res.setDoctorName(doctorDetail.getName());
                res.setDoctorPhone(doctorDetail.getMobileNumber());
                res.setMechanName(doctorDetail.getMechanName());
                res.setOrderPrice(BigDecimalUtils.divide(item.getOrderPrice(), 100));
                res.setIncome(BigDecimalUtils.divide(item.getIncome(), 100));
                res.setStatus("已签收");
                switch (item.getSourceType()) {
                    case "1":
                        res.setSourceType("线下医生处方");
                        break;
                    case "2":
                        res.setSourceType("线下智能处方");
                        break;
                    case "3":
                        res.setSourceType("互联网医生处方");
                        break;
                    case "4":
                        res.setSourceType("互联网智能处方");
                        break;
                    case "5":
                        res.setSourceType("互联网问诊");
                        break;
                }
                switch (item.getType()) {
                    case 1:
                        res.setType("线下诊金");
                        break;
                    case 2:
                        res.setType("管理计划服务费");
                        break;
                    case 3:
                        res.setType("服务费");
                        break;
                    case 6:
                        res.setType("图文咨询");
                        break;
                    case 7:
                        res.setType("图文问诊");
                        break;
                }
                switch (item.getSettlementStatus()) {
                    case 1:
                        res.setSettlementStatus("待结算");
                        break;
                    case 2:
                        res.setSettlementStatus("已结算");
                        break;
                    case 3:
                        res.setSettlementStatus("不予结算");
                        break;
                }
//                res.setNo(no);
                listRes.add(res);
                no++;
            }
            req.setPage(req.getPage() + 1);
        } while (iPage.getCurrent() < iPage.getPages());
        String title = doctorDetail.getName() + "医生收益明细表";
        if (StringUtils.isNotBlank(req.getWithdrawNo())) {
            title = doctorDetail.getName() + "医生提现订单结算报表";
        }
        try {
            ExtUtils.exportExcel(listRes, title, title, DoctorOrderIncomeDetailSystemExcelRes.class, title, true, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加诊疗分成
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addConsultOrderIncomeDetail(OrderPay orderPay) {
        ConsultSubscribe consultSubscribe = consultSubscribeService.getById(orderPay.getServerNo());
        log.info("入账医生收入明细问诊订单数据:{}", consultSubscribe);
        List<DoctorOrderIncomeDetail> list = new ArrayList<>();
        if (orderPay.getStatus() == OrderConstants.Status.PAY) {
            DoctorOrderIncomeDetail incomeDetail = new DoctorOrderIncomeDetail();
            Integer totalFee = orderPay.getTotalFee();
            log.info("诊疗订单总金额{}", totalFee);
            int afterTaxTotalIncome = BigDecimalUtils.divide(BigDecimal.valueOf(totalFee), afterTaxScale, 0).intValue();
            if (totalFee != 0) {
                Integer type = consultSubscribe.getType();
                if (type == 1) {
                    incomeDetail.setTitle("图文问诊");
                    incomeDetail.setType(OrderConstants.DoctorIncomeType.INQUIRY);
                } else if (type == 2) {
                    incomeDetail.setTitle("图文咨询");
                    incomeDetail.setType(OrderConstants.DoctorIncomeType.CONSULT);
                }
                incomeDetail.setDoctorId(consultSubscribe.getDoctorId());
                incomeDetail.setTencode(orderPay.getServerNo());
                incomeDetail.setOrderNo(orderPay.getOrderNo());
                incomeDetail.setIncome(totalFee);
                incomeDetail.setStatus(OrderConstants.DoctorIncomeStatus.FROZEN);
                incomeDetail.setTotalIncome(totalFee);
                incomeDetail.setAfterTaxTotalIncome(afterTaxTotalIncome);
                incomeDetail.setCreateDate(LocalDateTime.now());
                list.add(incomeDetail);
            }
        } else if (orderPay.getStatus() == OrderConstants.Status.FULLREFUND) {
            QueryWrapper<DoctorOrderIncomeDetail> qws = new QueryWrapper<>();
            qws.lambda().eq(DoctorOrderIncomeDetail::getOrderNo, orderPay.getOrderNo());
            qws.lambda().eq(DoctorOrderIncomeDetail::getTencode, consultSubscribe.getId());
            qws.lambda().eq(DoctorOrderIncomeDetail::getDoctorId, consultSubscribe.getDoctorId());
            qws.lambda().eq(DoctorOrderIncomeDetail::getRefund, 0);
            DoctorOrderIncomeDetail item = this.getOne(qws);
            if (item != null) {
                DoctorOrderIncomeDetail items = new DoctorOrderIncomeDetail();
                items.setId(item.getId());
                items.setStatus(OrderConstants.DoctorIncomeStatus.ENTER_FAIL);
                list.add(items);
                item.setId(null);
                item.setRefund(1);
                item.setIncome(-item.getIncome());
                item.setCreateDate(LocalDateTime.now());
                list.add(item);
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            saveOrUpdateBatch(list);
        }
    }

    /**
     * @param :
     * @return void
     * @description 手动重置医生收益记录
     * @author czg
     * @date 2023/11/30 19:01
     */
    @Override
    public void setAllOrderToIncomeDetail() {
        QueryWrapper<OrderPay> qw = new QueryWrapper<>();
        qw.lambda().eq(OrderPay::getStatus, OrderConstants.Status.PAY);
        List<OrderPay> list = orderPayService.list(qw);
        list.forEach(item -> {
            addDoctorOrderIncomeDetail(item);
        });
    }

    @Override
    public PageVo<DoctorOrderIncomePageRes> queryDoctorIncomePage(DoctorOrderIncomePageReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        req.setDoctorId(loginInfo.getId());
        PageVo<DoctorOrderIncomePageRes> pageVo = req.pageVoPojo();
        pageVo = this.getBaseMapper().queryDoctorIncomePage(pageVo, req);
        DoctorOrderIncomeStatisticsRes statisticsRes = new DoctorOrderIncomeStatisticsRes();
        Integer totalIncome = 0;
        Integer totalServiceIncome = 0;
        Integer totalPresIncome = 0;
        List<DoctorOrderIncomePageRes> list = this.getBaseMapper().queryDoctorIncomeList(req);
        if (CollectionUtils.isNotEmpty(list)) {
            for (DoctorOrderIncomePageRes item : list) {
                if (item.getRefund() == 1) {
                    item.setTotalIncome(item.getTotalIncome() == 0 ? 0 : -item.getTotalIncome());
                }
                totalPresIncome = item.getPresIncome() == null ? 0 : item.getPresIncome() + totalPresIncome;
                totalServiceIncome = item.getServiceIncome() == null ? 0 : item.getServiceIncome() + totalServiceIncome;
                totalIncome = totalIncome + item.getTotalIncome();
            }
        }
        statisticsRes.setTotalServiceIncome(totalServiceIncome);
        statisticsRes.setTotalIncome(totalIncome);
        statisticsRes.setTotalPresIncome(totalPresIncome);
        pageVo.setExtend(statisticsRes);
        return pageVo;
    }

    @Override
    public PageVo<DoctorWithdrawRecordPageSystemRes> queryWithdrawRecordPage(DoctorWithdrawPageReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        req.setDoctorId(loginInfo.getId());
        PageVo<DoctorWithdrawRecordPageSystemRes> pageVo = req.pageVoPojo();
        pageVo = this.getBaseMapper().queryWithdrawRecordPage(pageVo, req);
        return pageVo;
    }

    /**
     * 通过处方编号生成医生订单收入
     *
     * @param orderPay
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDoctorOrderIncomeDetail(OrderPay orderPay) {
        List<DoctorOrderIncomeDetail> list = new ArrayList<>();
        PresPrescription pres = presPrescriptionService.getById(orderPay.getServerNo());
        log.info("入账医生收入明细处方数据:{}", pres);
        if (pres == null) {
            log.error("入账医生收入明细处方数据为空:{}", orderPay.getOrderNo());
            return;
        }
        if (orderPay.getStatus() == OrderConstants.Status.PAY) {
            int consultationIncome = pres.getConsultationFee() != null ? pres.getConsultationFee() : 0;
            int serviceIncome = pres.getServiceFee() != null ? pres.getServiceFee() : 0;
            int drugsIncome = 0;
            int reviewDocDrugFee = 0;
            FinanceRatioSet financeRatioSet = financeRatioSetService.getFinanceDetail();
            if (financeRatioSet != null && financeRatioSet.getDoctorDrugRatio() != null) {
                Integer money = pres.getMoney();
                if (pres.getDiscountMoney() != null) {
                    money = !pres.getMoney().equals(pres.getDiscountMoney()) ? pres.getDiscountMoney() : pres.getMoney();
                }
                BigDecimal income = BigDecimalUtils.multiply(BigDecimal.valueOf(money), financeRatioSet.getDoctorDrugRatio());
                drugsIncome = BigDecimalUtils.divide(income, BigDecimal.valueOf(100), 0).intValue();
                if (!pres.getDoctorId().equals(pres.getReviewDoctorId())) {
//                    reviewDocDrugFee = BigDecimalUtils.multiply(BigDecimal.valueOf(drugsIncome), BigDecimal.valueOf(0.3), 0).intValue();
//                    drugsIncome = drugsIncome - reviewDocDrugFee;
                }
            }
            Integer presPresOriginalMoney = pres.getPresOriginalMoney();
            log.info("诊疗费:{},服务费:{},药品费:{},审核医生药品费用:{},药品原价费用:{}", consultationIncome, serviceIncome, drugsIncome, reviewDocDrugFee, presPresOriginalMoney);
            int totalIncome = consultationIncome + serviceIncome + drugsIncome;
            int afterTaxTotalIncome = BigDecimalUtils.divide(BigDecimal.valueOf(totalIncome), afterTaxScale, 0).intValue();
            DoctorOrderIncomeDetail incomeDetail;
            if (consultationIncome != 0) {
                incomeDetail = new DoctorOrderIncomeDetail();
                incomeDetail.setTitle("处方诊金");
                incomeDetail.setDoctorId(pres.getDoctorId());
                incomeDetail.setTencode(orderPay.getServerNo());
                incomeDetail.setOrderNo(orderPay.getOrderNo());
                incomeDetail.setIncome(consultationIncome);
                incomeDetail.setType(OrderConstants.DoctorIncomeType.CONSULTATION_FEE);
                incomeDetail.setStatus(OrderConstants.DoctorIncomeStatus.FROZEN);
                incomeDetail.setTotalIncome(totalIncome);
                incomeDetail.setAfterTaxTotalIncome(afterTaxTotalIncome);
                incomeDetail.setCreateDate(LocalDateTime.now());
                incomeDetail.setSettlementStatus(OrderConstants.DoctorSettlementStatus.NO_TWO_SETTLEMENT);
                list.add(incomeDetail);
            }
            if (serviceIncome != 0) {
                incomeDetail = new DoctorOrderIncomeDetail();
                incomeDetail.setTitle("疾病管理费");
                incomeDetail.setDoctorId(pres.getDoctorId());
                incomeDetail.setTencode(orderPay.getServerNo());
                incomeDetail.setOrderNo(orderPay.getOrderNo());
                incomeDetail.setIncome(serviceIncome);
                incomeDetail.setStatus(OrderConstants.DoctorIncomeStatus.FROZEN);
                incomeDetail.setType(OrderConstants.DoctorIncomeType.SERVICE_FEE);
                incomeDetail.setTotalIncome(totalIncome);
                incomeDetail.setAfterTaxTotalIncome(afterTaxTotalIncome);
                incomeDetail.setSettlementStatus(OrderConstants.DoctorSettlementStatus.NO_TWO_SETTLEMENT);
                incomeDetail.setCreateDate(LocalDateTime.now());
                list.add(incomeDetail);
            }
            if (drugsIncome != 0) {
                incomeDetail = new DoctorOrderIncomeDetail();
                incomeDetail.setTitle("管理计划推广费");
                incomeDetail.setDoctorId(pres.getDoctorId());
                incomeDetail.setTencode(orderPay.getServerNo());
                incomeDetail.setOrderNo(orderPay.getOrderNo());
                incomeDetail.setIncome(drugsIncome);
                incomeDetail.setPresOriginalPrice(presPresOriginalMoney);
                incomeDetail.setStatus(OrderConstants.DoctorIncomeStatus.FROZEN);
                incomeDetail.setType(OrderConstants.DoctorIncomeType.DRUGS_FEE);
                incomeDetail.setTotalIncome(totalIncome);
                incomeDetail.setAfterTaxTotalIncome(afterTaxTotalIncome);
                incomeDetail.setSettlementStatus(OrderConstants.DoctorSettlementStatus.NO_TWO_SETTLEMENT);
                incomeDetail.setCreateDate(LocalDateTime.now());
                list.add(incomeDetail);
                if (reviewDocDrugFee != 0) {
                    Integer doctorId = pres.getDoctorId();
                    LambdaQueryWrapper<DoctorDetail> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(DoctorDetail::getDoctorId, doctorId);
                    DoctorDetail doctorDetail = doctorDetailService.getOne(queryWrapper);
                    Integer qualificationType = doctorDetail.getQualificationType();
                    if (qualificationType == UserConstants.QualificationType.COUNTRY || qualificationType == UserConstants.QualificationType.PRACTICE) {
                        incomeDetail = new DoctorOrderIncomeDetail();
                        incomeDetail.setTitle("审方劳务收益");
                        incomeDetail.setDoctorId(pres.getReviewDoctorId());
                        incomeDetail.setTencode(orderPay.getServerNo());
                        incomeDetail.setOrderNo(orderPay.getOrderNo());
                        incomeDetail.setIncome(reviewDocDrugFee);
                        incomeDetail.setStatus(OrderConstants.DoctorIncomeStatus.FROZEN);
                        incomeDetail.setType(OrderConstants.DoctorIncomeType.REVIEW_PRES_FEE);
                        incomeDetail.setTotalIncome(reviewDocDrugFee);
                        incomeDetail.setAfterTaxTotalIncome(BigDecimalUtils.divide(BigDecimal.valueOf(reviewDocDrugFee), afterTaxScale, 0).intValue());
                        incomeDetail.setCreateDate(LocalDateTime.now());
                        incomeDetail.setSettlementStatus(OrderConstants.DoctorSettlementStatus.NO_TWO_SETTLEMENT);
                        list.add(incomeDetail);
                    }
                }
            }
        } else if (orderPay.getStatus() == OrderConstants.Status.FULLREFUND) {
            QueryWrapper<DoctorOrderIncomeDetail> qws = new QueryWrapper<>();
            qws.lambda().nested(t -> t.eq(DoctorOrderIncomeDetail::getDoctorId, pres.getDoctorId()).or().eq(DoctorOrderIncomeDetail::getDoctorId, pres.getReviewDoctorId()));
            qws.lambda().eq(DoctorOrderIncomeDetail::getOrderNo, orderPay.getOrderNo());
            qws.lambda().eq(DoctorOrderIncomeDetail::getTencode, pres.getTencode());
            qws.lambda().eq(DoctorOrderIncomeDetail::getRefund, 0);
            List<DoctorOrderIncomeDetail> temps = list(qws);
            if (temps != null) {
                for (DoctorOrderIncomeDetail item : temps) {
                    DoctorOrderIncomeDetail items = new DoctorOrderIncomeDetail();
                    items.setId(item.getId());
                    items.setStatus(OrderConstants.DoctorIncomeStatus.ENTER_FAIL);
                    items.setSettlementStatus(OrderConstants.DoctorSettlementStatus.NO_ONE_SETTLEMENT);
                    list.add(items);
                    item.setId(null);
                    item.setRefund(1);
                    item.setIncome(-item.getIncome());
                    item.setCreateDate(LocalDateTime.now());
                    list.add(item);
                }
            }
        }
        log.info("收入数据批量添加或删除 数据:{}", list);
        saveOrUpdateBatch(list);
    }

    /**
     * 查询医生提现收入信息
     *
     * @param docId
     * @return
     */
    @Override
    public DoctorWithdrawIncomeInfoRes queryDoctorWithdrawIncomeInfo(Integer docId) {
        if (docId == null) {
            docId = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get().getId();
        }
        DoctorWithdrawIncomeInfoRes res = getBaseMapper().queryDoctorWithdrawIncomeInfo(docId);
        if (res == null) {
            res = new DoctorWithdrawIncomeInfoRes();
        }
        ObjectUtils.setBeanFiledDefaultValue(res);
        //税后计算
//        res.setAfterTaxTotalIncome(BigDecimalUtils.multiply(BigDecimal.valueOf(res.getTotalIncome()), afterTaxScale, 0).intValue());
//        res.setCanWithdrawIncome(BigDecimalUtils.multiply(BigDecimal.valueOf(res.getTotalIncome() - res.getTotalWithdrawIncome()), afterTaxScale, 0).intValue());
        //不显示负数
        int totalIncome = 0;
        if (res.getAfterTaxTotalIncome() - res.getAfterTaxTotalWithdrawIncome() > 0) {
            totalIncome = res.getAfterTaxTotalIncome() - res.getAfterTaxTotalWithdrawIncome();
        }
        res.setCanWithdrawIncome(totalIncome);
        return res;
    }

    /**
     * 医生收入入账成功
     *
     * @param tencode
     * @param doctorId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doctorOrderIncomeEntrySuc(String tencode, Integer doctorId) {
        QueryWrapper<DoctorOrderIncomeDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorOrderIncomeDetail::getTencode, tencode);
        qw.lambda().eq(DoctorOrderIncomeDetail::getDoctorId, doctorId);
        qw.lambda().eq(DoctorOrderIncomeDetail::getStatus, OrderConstants.DoctorIncomeStatus.FROZEN);
        qw.lambda().eq(DoctorOrderIncomeDetail::getRefund, 0);
        int count = count(qw);
        if (count == 0) {
            log.info("tencode:{},doctorId:{}:入账失败,未查询的冻结中的收入明细", tencode, doctorId);
            return;
        }
        DoctorOrderIncomeDetail update = new DoctorOrderIncomeDetail();
        update.setStatus(OrderConstants.DoctorIncomeStatus.WITHDRAW);
        update(update, qw);
    }
}
